<?php

class Plugin {

    protected static $plugins = array();
    protected static $sys = 'unix';
    protected $pluginData = array();
    protected $ci;
    protected $plugin;

    public function __construct($class = null) {

        $this->ci =& get_instance();
        $this->plugin = $class;

        if (!is_null($class))
            log_message('Debug', 'Loaded ' . $class);
    }

    public function setPluginData($values) {
        foreach ($values as $key => $value) {
            $this->$key = $value;
        }
    }

    protected function execute($cmd = null) {
        if (!is_null($cmd)) {
            if (Plugin::$sys == 'unix') {
                return shell_exec($cmd);
            }
        } else {
            return false;
        }
    }

    public function getPlugin() {
        return $this->plugin;
    }

    protected function loadView($view, $data = array(), $return = false) {
        return $this->ci->load->view('', $data, $return, 'plugins/' . $this->plugin . '/views/' . $view . EXT);
    }

    public static function registerPlugin($plugin) {

        $plugin = strtolower($plugin);

        if (!in_array($plugin, self::$plugins)) {

            $classPath = 'plugins/' . $plugin . '/libraries/class' . EXT;

            if (file_exists($classPath)) {
                include_once($classPath);
            }
        }
    }

    public static function installPlugin($plugin) {
        $plugin = strtolower($plugin);
        $xmlPath = 'plugins/' . $plugin . '/info.xml';

        if (file_exists($xmlPath)) {
            $xml = simplexml_load_file($xmlPath);

            $pluginObject = new MPlugin();
            $pluginObject->get_by_name((string) $xml->name);

            if (!$pluginObject->exists()) {
                foreach (array('name', 'call', 'description') as $key => $value) {
                    $pluginObject->$value = (string) $xml->$value;
                }

                $pluginObject->save();

                foreach ($xml->functions->function as $function) {
                    $functionObject = new MFunction();
                    $functionObject->name = (string) $function->name;
                    $functionObject->call = (string) $function->call;

                    $functionObject->save(array('plugin' => $pluginObject));
                    $functionObject->clear();
                }
            } else {
                
            }

            return $pluginObject->id;
        } else {
            return false;
        }
    }

    public static function pluginExists($plugin) {
        return in_array($plugin, self::$plugins);
    }

    public static function getPlugins() {
        return self::$plugins;
    }

}